package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyThemeObjcet;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    @Autowired
    private MongoTemplate template;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private RegionRepository regionRepository;
    @Override
    public StrategyTheme get(String id) {
        return  strategyThemeRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        List<StrategyTheme> list = strategyThemeRepository.findAll();
        return list;
    }



    @Override
    public Page<StrategyTheme> query(StrategyThemeObjcet qo) {
        //创建查询对象
        Query query = new Query();
        //分页查询

        PageRequest request = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //关键字查询
        if(StringUtils.hasLength(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(".*"+qo.getKeyword()+".*"));
        }
       return DBHelper.query(template,StrategyTheme.class,query,request);
    }


    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if(strategyTheme.getId()==null){
            this.save(strategyTheme);
        }else{
            this.update(strategyTheme);
        }
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }




}
